<template>
  <div class="trends-chart-container">
    <div class="chart-header-container">
      <div class="chart-title">Sentiment trends</div>
      <div style="display: flex; align-items: center">
        <el-checkbox
          v-for="city in cityOptions"
          :label="city"
          :key="city"
          class="checkbox-item"
          v-model="checkedCities"
          @change="handleCheckedCitiesChange(checkedCities)"
          >{{ city }}</el-checkbox
        >
        <div class="trends-chart__refresh-container">
          <el-dropdown class="trends-chart__refresh-dropdown" trigger="click">
            <!-- 触发图标 -->
            <img
              src="@/assets/fresh.png"
              alt="Refresh"
              class="trends-chart__refresh-icon"
            />

            <!-- 多选菜单 -->
            <el-dropdown-menu
              slot="dropdown"
              class="trends-chart__multi-select"
              style="font-family: 'Inter Variable', sans-serif"
            >
              <el-checkbox-group
                style="display: flex; flex-direction: column; padding: 0 10px"
                v-model="selectedServices"
                @change="handleServiceSelectionChange"
              >
                <el-checkbox
                  v-for="service in serviceOptions"
                  :label="service.value"
                  :key="service.label"
                  >{{ service.label }}</el-checkbox
                >
              </el-checkbox-group>
            </el-dropdown-menu>
          </el-dropdown>
        </div>
      </div>
    </div>
    <!-- 图表展示区域 -->
    <div class="chart-graph">
      <PieChart :option="optionLineGraph" :height="'300px'"></PieChart>
    </div>
  </div>
</template>

<script>
import PieChart from "@components/common/PieChart.vue";
import { fontChart } from "@/utils/echartPxToRem";
export default {
  components: {
    PieChart,
  },
  data() {
    return {
      timeSelect: "",
      checked: false,
      selectedServices: [], // 存储选中的服务值
      serviceOptions: [
        { label: "Location", value: "Location" },
        { label: "Cleanness", value: "Cleanness" },
        { label: "Room", value: "Room" },
        { label: "Hotel Amenities", value: "Hotel Amenities" },
        { label: "F&B", value: "F&B" },
        { label: "Service", value: "Service" },
        { label: "Value for money", value: "Value for money" },
      ],
      options: [
        {
          value: "1",
          label: "一月份",
        },
        {
          value: "2",
          label: "二月份",
        },
      ],
      checked: false,
      checkedCities: [],
      cityOptions: [
        "Avg of city",
        "Avg of the competitors",
        "Avg of the portfolio",
        "Avg of the brands",
        "Previous Period",
      ],
      cityAverageData: {
        "Avg of city": {
          name: "Avg of city",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          lineStyle: {
            color: "#454545",
            width: 3,
            type: "dashed",
            dashArray: [12, 4], // 长虚线 + 中等间隔
          },
          data: [4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4, 4],
        },
        "Avg of the competitors": {
          name: "Avg of the competitors",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          lineStyle: {
            color: "#454545",
            width: 2.5,
            type: "dashed",
            dashArray: [4, 2], // 短虚线 + 小间隔
          },
          data: [5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5, 5],
        },
        "Avg of the portfolio": {
          name: "Avg of the portfolio",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          lineStyle: {
            color: "#454545",
            width: 2,
            type: "dashed",
            dashArray: [2, 1, 8, 1], // 点 + 长间隔 + 点
          },
          data: [6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6, 6],
        },
        "Avg of the brands": {
          name: "Avg of the brands",
          type: "line",
          symbol: "none",
          yAxisIndex: 0,
          lineStyle: {
            color: "#454545",
            width: 1.5,
            type: "dashed",
            dashArray: [1, 1], // 密集点线
          },
          data: [8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8, 8],
        },
      },
      PREVIOUS_PERIOD_DATA: [
        {
          // 蓝色历史线
          name: "Historical Blue",
          type: "line",
          symbol: "none",
          smooth: true,
          yAxisIndex: 0,
          lineStyle: {
            color: "#CE4049",
            width: 1,
            type: "dashed",
            dash: [8, 4],
          },
          data: [4, 5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10], // 每月递增1，最后稳定
        },
        {
          // 紫色历史线
          name: "Historical Purple",
          type: "line",
          symbol: "none",
          smooth: true,
          yAxisIndex: 0,
          lineStyle: {
            color: "#EFB82C",
            width: 1,
            type: "dashed",
            dash: [8, 4],
          },
          data: [5, 5, 6, 6, 7, 7, 8, 8, 9, 9, 10, 10], // 每两月上一个台阶
        },
        {
          // 红色历史线
          name: "Historical Red",
          type: "line",
          symbol: "none",
          smooth: true,
          yAxisIndex: 0,
          lineStyle: {
            color: "#2FAA68",
            width: 1,
            type: "dashed",
            dash: [8, 4],
          },
          data: [7, 6, 8, 7, 9, 8, 10, 9, 8, 9, 8, 9], // 在6-10之间小幅波动
        },
      ],
      optionLineGraph: {
        subtitle: {
          text: "by scores",
        },

        grid: {
          left: "0%",
          right: "1%",
          bottom: "3%",
          top: "13%",
          containLabel: true,
        },
        xAxis: {
          type: "category",
          boundaryGap: false,
          data: [
            "Jan",
            "Feb",
            "Mar",
            "Apr",
            "May",
            "June",
            "July",
            "Aug",
            "Sept",
            "Oct",
            "Nov",
            "Dec",
          ],
          axisLine: {
            show: false,
          },
          axisTick: {
            show: false,
            alignWithLabel: true, // 使刻度线与标签对齐
          },
          axisLabel: {
            margin: 20, // 关键：增加标签与 Y 轴的间距（原值可能为 0 或较小）
            color: "#6a6969",
            fontSize: fontChart(12),
          },
        },
        yAxis: [
          {
            type: "value", // 数值轴（用于连续数据）
            axisTick: {
              inside: true, // 刻度线朝内（朝向图表区域）
              interval: 10, // 刻度线间隔（此处可能无效，因 min/max/interval 已定义）
            },
            axisLabel: {
              align: "right", // 刻度标签水平对齐：右对齐（贴近轴线）
              margin: 16, // 标签与轴线的距离（单位：像素）
              color: "#6a6969", // 标签文字颜色
              fontSize: 12, // 标签文字大小
              overflow: "truncate", // 文字溢出时截断显示
              fontWeight: 400, // 文字粗细（正常）
            },
            name: "by scores", // 坐标轴名称
            nameGap: 20, // 名称与轴线的距离（单位：像素）
            min: 1, // 坐标轴最小值
            max: 10, // 坐标轴最大值
            interval: 1, // 刻度间隔（相邻刻度的差值）
            position: "left", // 坐标轴位置：左侧
            splitLine: {
              show: false, // 不显示网格线
            },
            nameTextStyle: {
              fontSize: 14, // 名称文字大小
              fontWeight: 400, // 文字粗细
              padding: [0, -2, 0, 0],
            },
          },

          {
            type: "value", // 数值轴
            name: "#of staff logs", // 坐标轴名称
            nameGap: 20, // 名称与轴线的距离（单位：像素）
            min: 0, // 最小值
            max: 100, // 最大值
            offset: 30, // 坐标轴偏移量（与左侧坐标轴的水平距离，避免重叠）
            interval: 10, // 刻度间隔（如 0, 10, 20, ...）
            position: "right", // 坐标轴位置：右侧
            splitLine: {
              show: false, // 不显示网格线
            },
            axisLabel: {
              align: "right", // 刻度标签水平对齐：右对齐（因在右侧，实际靠左显示）
            },
            nameTextStyle: {
              fontSize: 14, // 名称文字大小
              color: "#230229", // 名称文字颜色
              fontWeight: 400, // 文字粗细
              align: "right", // 旋转后文字的水平对齐：右对齐（文字右侧贴近轴线）
              verticalAlign: "middle", // 旋转后文字的垂直对齐：居中
              rotate: 90, // 文字旋转角度（-90度：垂直向上，向左显示）
              padding: [0, -7, 0, 0], // 文字内边距（上、右、下、左）
            },
          },
        ],
        emphasis: {
          lineStyle: {
            width: 4,
          },
        },
        series: [
          {
            name: "Positive",
            type: "line",
            data: [8, 8, 9, 9, 8, 9, 9, 8, 9, 8, 9, 9],

            yAxisIndex: 0,

            smooth: true,
            symbol: "none",
            lineStyle: {
              color: "#2FAA68",
              width: 2,
            },
            emphasis: {
              lineStyle: {
                width: 3, // 鼠标移入时的线宽
              },
            },
            markPoint: {
              symbol: `image://${require("@/assets/pos.png")}`,
              symbolSize: [18, 18],
              symbolOffset: [0, -12],
              data: [
                {
                  type: "max", // 标记最大值
                  name: "最高点",
                },
              ],
              label: {
                show: false, // 隐藏标签
              },
            },
            markArea: {
              silent: true, // 禁用 markArea 的事件
              itemStyle: {
                color: " rgba(247, 11, 11, 0.07)  ",
              },
              data: [
                [
                  {
                    xAxis: "Jan",
                    yAxis: 1,
                  },
                  {
                    xAxis: "Dec",
                    yAxis: 7,
                  },
                ],
              ],
            },
          },
          {
            name: "Neutral",
            type: "line",
            data: [6, 7, 7, 6, 7, 6, 7, 6, 7, 6, 7, 6],
            yAxisIndex: 0,
            smooth: true,
            symbol: "none", // 不显示小圆点
            lineStyle: {
              color: "#EFB82C",
              width: 2,
            },
            emphasis: {
              lineStyle: {
                width: 3, // 鼠标移入时的线宽
              },
            },
            markPoint: {
              silent: true, // 禁用 markArea 的事件
              symbol: `image://${require("@/assets/neu.png")}`,
              symbolSize: [18, 18],
              symbolOffset: [0, -12],
              data: [
                {
                  type: "max", // 标记最大值
                  name: "最高点",
                },
              ],
              label: {
                show: false, // 隐藏标签
              },
            },
            markArea: {
              itemStyle: {
                color: " rgba(243, 176, 7, 0.08) ",
              },
              data: [
                [
                  {
                    xAxis: "Jan",
                    yAxis: 7,
                  },
                  {
                    xAxis: "Dec",
                    yAxis: 8.5,
                  },
                ],
              ],
            },
          },
          {
            name: "Negative",
            type: "line",
            data: [2, 5, 3, 7, 6, 5, 6, 7, 8, 6, 8, 5], // 前6个月下降，后6个月回升

            yAxisIndex: 0,
            smooth: true,
            symbol: "none", // 不显示小圆点
            lineStyle: {
              color: "#CE4049",
              width: 2,
            },
            emphasis: {
              lineStyle: {
                width: 3, // 鼠标移入时的线宽
              },
            },
            markPoint: {
              silent: true, // 禁用 markArea 的事件
              symbol: `image://${require("@/assets/neg.png")}`,
              symbolSize: [18, 18],
              symbolOffset: [0, -12],
              data: [
                {
                  type: "max", // 标记最大值
                  name: "最高点",
                },
              ],
              label: {
                show: false, // 隐藏标签
              },
            },
            markArea: {
              itemStyle: {
                color: "rgba(7, 240, 17, 0.08)  ",
              },
              data: [
                [
                  {
                    xAxis: "Jan",
                    yAxis: 8.5,
                  },
                  {
                    xAxis: "Dec",
                    yAxis: 10,
                  },
                ],
              ],
            },
          },
        ],
      },
    };
  },
  methods: {
    // 处理下拉菜单中的多选变化
    handleServiceSelectionChange(values) {
      console.log("选中的服务:", values);
      // 这里可以添加根据选中服务更新图表或其他逻辑
    },

    handlePlatformSelect(service) {
      console.log("选择的服务:", service);
      // 无需手动关闭菜单，Element UI自动处理
    },
    handleCheckedCitiesChange(checkedValues) {
      const avgOptions = checkedValues.filter(
        (option) => option !== "Previous Period"
      );
      const showHistory = checkedValues.includes("Previous Period");

      // 直接从配置中获取原始系列（确保包含所有三个基础系列）
      const originalSeries = [
        // 深拷贝原始系列配置，避免引用问题
        { ...this.optionLineGraph.series[0] }, // LinkedIn
        { ...this.optionLineGraph.series[1] }, // Brand Purple
        { ...this.optionLineGraph.series[2] }, // YouTube
      ];

      // 获取平均值系列
      const avgSeries = Object.values(this.cityAverageData).filter((series) =>
        avgOptions.includes(series.name)
      );

      // 获取历史系列
      const historySeries = showHistory
        ? this.PREVIOUS_PERIOD_DATA.filter((series) =>
            series.name.startsWith("Historical")
          )
        : [];

      // 合并所有系列
      this.optionLineGraph = {
        ...this.optionLineGraph,
        series: [...originalSeries, ...avgSeries, ...historySeries],
      };
    },
  },
  // PieChart.vue
  // mounted() {
  //   if (!this.optionLineGraph) {
  //     console.warn("ECharts option 为空，跳过初始化");
  //     return;
  //   }

  //   // 初始化图表
  //   this.chart = echarts.init(this.$el.querySelector(".chart-graph"));
  //   this.chart.setOption(this.optionLineGraph);

  //   // 添加点击事件
  //   this.chart.on("click", (params) => {
  //     console.log("点击了", params.seriesName);
  //   });

  //   // 监听窗口大小变化，调整图表
  //   window.addEventListener("resize", () => {
  //     if (this.chart) this.chart.resize();
  //   });
  // },

  // beforeDestroy() {
  //   // 销毁前释放图表资源
  //   if (this.chart) {
  //     this.chart.dispose();
  //     this.chart = null;
  //   }
  // },
};
</script>

<style scoped lang="scss">
.trends-chart-container {
  margin-top: 20px;
  display: flex;
  flex-direction: column;
  padding: 16px 42px;
  align-items: center;
  justify-content: space-between;
  background: #ffffff;
  border: 1px solid #cdcccc;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgb(0 0 0 / 5%);

  .chart-header-container {
    align-items: center;
    width: 100%;
    display: flex;
    justify-content: space-between;

    .chart-title {
      font-size: 20px;
      font-weight: 600;
      color: #454545;
    }

    .refresh-and-checkbox-container {
      display: flex;
      align-items: center;
      justify-content: space-between;
      .city-average-label {
        padding: 8px;
        background: #058287;
        color: #fff;
        font-size: 12px;
        font-weight: 400;
        margin-right: 13px;
        border-radius: 8px;
      }

      .brands-average-label {
        padding: 8px;
        background: #bb8b11;
        color: #fff;
        font-size: 12px;
        font-weight: 400;
        margin-right: 13px;
        border-radius: 8px;
      }
      .portfolio-average-label {
        padding: 8px;
        background: #a601f1;
        color: #fff;
        font-size: 12px;
        font-weight: 400;
        margin-right: 13px;
        border-radius: 8px;
      }
      .competitors-average-label {
        padding: 8px;
        background: #4199e1;
        color: #fff;
        font-size: 12px;
        font-weight: 400;
        margin-right: 13px;
        border-radius: 8px;
      }
    }

    .checkbox-container {
      el-checkbox {
        font-weight: 400;
        font-size: 14px;
        color: #232323;
      }
    }

    .refresh-icon-container {
      margin-left: 24px;
      cursor: pointer;
    }
  }

  .chart-graph {
    width: 100%;
  }
  /* 新增：复选框样式调整 */

  .el-checkbox {
    font-size: 14px;
    font-weight: 400;
    color: #232323;
    margin-right: 24px; /* 增加复选框间距 */
    white-space: nowrap; /* 防止文字换行 */

    &:last-child {
      margin-right: 0; /* 最后一个复选框取消右侧间距 */
    }

    .el-checkbox__input {
      vertical-align: middle; /* 图标垂直居中 */
      margin-right: 6px; /* 图标与文字间距 */
    }

    .el-checkbox__label {
      vertical-align: middle;
      font-family: "Inter Variable", sans-serif;
      font-size: 0.0972rem;
    }
    ::v-deep .el-checkbox__inner {
      border: 1px solid #6a6969 !important;
    }
  }
  // 穿透 scoped 作用域，设置鼠标移入效果
  ::v-deep .trends-chart__refresh-icon:hover {
    opacity: 0.7;
    cursor: pointer; // 鼠标变为手型提示可点击
  }
}
</style>

<style lang="scss">
.trends-chart__multi-select {
  /* 复选框图标与文本的间距 */
  .el-checkbox__input {
    margin-right: 15px !important;
    margin-top: 5px;
  }
}
</style>
